--EventCenter
--[[
	事件系统：自定义单例 + 自定义字典容器
--]]

require 'Class'
require 'HTDictionary'

--事件类型（Enum）
EventType = {
	Player_Lv_Up_1 = 1,
	Player_Kill_Count_Add_1 = 2,
	Ping_out = 3,
	NUM = 4,
}

EventCenter = Singleton:GetInstance()  --事件中心（单例）
EventCenter.containner = Dictionary:New()  --容器
EventCenter.Subscribe = function(self,eventType,callback)  --注册
	if not callback or type(callback) ~= 'function' then
		print('Error: Subscribe callback invaild.')
		return
	end
	if self.containner:ContainsKey(eventType) then
		table.insert(self.containner[eventType],callback)
	else
		local mutilDelegate = {}
		table.insert(mutilDelegate,callback)
		self.containner:Add(eventType,mutilDelegate)
	end
end
EventCenter.Unsubscribe = function(self,eventType,callback)  --注销
	if not callback or type(callback) ~= 'function' then
		print('Error: Unsubscribe callback invaild.')
		return
	end
	if self.containner:ContainsKey(eventType) == false then return end
	for i = #self.containner[eventType],1,-1 do
		if self.containner[eventType][i] == callback then
			table.remove(self.containner[eventType],i)
			if #self.containner[eventType] <= 0 then
				self.containner:Remove(eventType)
			end
			return
		end
	end
end
EventCenter.Fire = function(self,eventType,...)  --发送事件
	if self.containner:ContainsKey(eventType) == false then return end
	for k,v in pairs(self.containner[eventType]) do
		v(...)
	end
end

--------Main--------
PlayerModule = Class()  --玩家模块

PlayerModule.Init = function(self)
	EventCenter:GetInstance():Subscribe(EventType.Player_Lv_Up_1,self.Player_Lv_Up_Cb)
end
PlayerModule.Player_Lv_Up_Cb = function(times)
	print(string.format('玩家升级了：%d次',times))
end
PlayerModule.BeforeDestory = function(self)
	EventCenter:GetInstance():Unsubscribe(EventType.Player_Lv_Up_1,self.Player_Lv_Up_Cb)  --注销事件
end

BattleModule = Class()  --战斗模块
BattleModule.Init = function(self)
	EventCenter:GetInstance():Subscribe(EventType.Player_Kill_Count_Add_1,self.Battle_Kill_Enemy_Cb)
	EventCenter:GetInstance():Subscribe(EventType.Player_Lv_Up_1,self.Battle_Player_Lv_Up_Cb)
end
BattleModule.Battle_Kill_Enemy_Cb = function(nums)
	print(string.format('玩家击败了%d个敌人',nums))
end
BattleModule.Battle_Player_Lv_Up_Cb = function(times)
	print(string.format('战斗让玩家升级了：%d次',times))
end
BattleModule.BeforeDestory = function(self)
	EventCenter:GetInstance():Unsubscribe(EventType.Player_Lv_Up_1,self.Battle_Player_Lv_Up_Cb)  --注销事件
end

function main()
	playerModule = PlayerModule:New()
	playerModule:Init()
	battleModule = BattleModule:New()
	battleModule:Init()
	EventCenter:GetInstance():Fire(EventType.Player_Lv_Up_1,5)  --玩家升级了：5次
																--战斗让玩家升级了：5次
	EventCenter:GetInstance():Fire(EventType.Player_Kill_Count_Add_1,10)  --玩家击败了10个敌人

	playerModule:BeforeDestory()  --注销事件
	EventCenter:GetInstance():Fire(EventType.Player_Lv_Up_1,8)  --战斗让玩家升级了：8次
	battleModule:BeforeDestory()  --注销事件
	EventCenter:GetInstance():Fire(EventType.Player_Lv_Up_1,5)  --
end

main()
